import TrieData from "../models/TrieData";

class TrieNode{
  constructor() {
    this.numPass = 0;
    this.numEnd = 0;
    this.edges = [];
    this.value = "";
    this.isEnd = false;
  }
}

class Trie{
  constructor(){
    this.root = new TrieNode();
  }
  insert(word) {
    var cur = this.root;
    for (var i = 0; i < word.length; i++) {
      var c = word.charCodeAt(i);
      c -= 48; //减少“0”的charCode
      var node = cur.edges[c];
      if (node == null) {
        var node = (cur.edges[c] = new TrieNode());
        node.value = word.charAt(i);
        node.numPass = 1; //有N个字符串经过它
      } else {
        node.numPass++;
      }
      cur = node;
    }
    cur.isEnd = true; //樯记有字符串到此节点已经结束
    cur.numEnd++; //这个字符串重复次数
    return true;
  }
  preTraversal(cb){
    function preTraversalImpl(root,str,cb){
      cb(root,str)
      for (let i = 0,n= root.edges.length;i<n;i++){
        let node = root.edges[i];
        if(node){
          preTraversalImpl(node,str+node.value,cb);
        }
      }
    }
    preTraversalImpl(this.root,"",cb);
  }
}
function getTrieFromMongo(callback){
  return TrieData.findOne((err,data)=>{
    let { name, keys } = data;
    var t = new Trie()
    for(let i =0;i<keys.length;i++){
      t.insert(keys[i])
    }
    callback(t)
  })
}
export default getTrieFromMongo
